package com.honey.chat.im;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.honey.chat.entity.ChatMsg;
import com.honey.chat.entity.User;

@ServerEndpoint(value = "/honeychat")
@Component
public class HoneyChat{

	//用来存放每个客户端对应的HoneyWebSocket对象。
    //private static CopyOnWriteArraySet<HoneyChat> webSocketSet = new CopyOnWriteArraySet<HoneyChat>();

	private static Map<String, HoneyChat> map = new HashMap<>();
	
	public static long userId=0;
	
	private Session session;
	
	private User user;
	
	@OnOpen
	public void onOpen(Session session) throws IOException {
		this.session=session;
		//webSocketSet.add(this);
		user=new User();
		user.setUserId(userId);
		userId++;
		user.setLoginName("honey"+user.getUserId());
		user.setAvatar("/img/1.png");
		map.put(session.getId(), this);
		ChatMsg chatMsg = new ChatMsg(10, 
				user.getLoginName()+":加入聊天室", 
				user.getLoginName(), 
				user.getAvatar(), 
				datetimeStr(new Date()),
				user.getUserId(),
				null);
		sendmsgallselelse(chatMsg);
	}
	
	@OnClose
	public void onClose(Session session) throws IOException {
		ChatMsg msg = new ChatMsg(11, 
				user.getLoginName()+":离开聊天室", 
				user.getLoginName(), 
				user.getAvatar(), 
				datetimeStr(new Date()),
				user.getUserId());
		sendmsgallnosel(msg.toString());
		//webSocketSet.remove(session);
		map.remove(session.getId());
	}
	
	@OnMessage
	public void onMessage(String msg,Session session) throws IOException {
		ChatMsg chatMsg = new ChatMsg(2, 
				msg.replace("\"","\\\""), 
				user.getLoginName(), 
				user.getAvatar(), 
				datetimeStr(new Date()),
				user.getUserId());
		sendmsgallnosel(chatMsg.toString());
	}
	
	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}

    //给自己发消息
    public void sendmsg(String message) throws IOException {
    	this.session.getBasicRemote().sendText(message);
    }

    //给所有人发送消息
	public void sendmsgall(String msg) throws IOException {
		for (HoneyChat honeyChat : map.values()) {
			if (honeyChat.session.isOpen()) {
				honeyChat.session.getAsyncRemote().sendText(msg);
			}
		}
	}
	
	//给除自己以外的所有人发送消息
	public void sendmsgallnosel(String msg) throws IOException {
		for (HoneyChat honeyChat : map.values()) {
			if (honeyChat.session.isOpen()) {
				if(honeyChat.session!=this.session) {
					honeyChat.session.getAsyncRemote().sendText(msg);
				}
			}
		}
	}
	
	//给所有人发送相同消息,自己另外消息
	public void sendmsgallselelse(ChatMsg msg) throws IOException {
		for (HoneyChat honeyChat : map.values()) {
			if (honeyChat.session.isOpen()) {
				if(honeyChat.session!=this.session) {
					honeyChat.session.getAsyncRemote().sendText(msg.toString());
				}else {
					List<User> users = new ArrayList<>();
					for (HoneyChat hChat : map.values()) {
						users.add(hChat.user);
					}
					msg.setType(12);
					msg.setUsers(users);
					honeyChat.session.getAsyncRemote().sendText(msg.toString().replace("\"[", "[").replace("]\"", "]"));
				}
			}
		}
	}
	
	public String datetimeStr(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(date);
	}
	
}
